import * as vscode from 'vscode';
import { kebabCase, pascalCase } from 'change-case'

export function cpDetailCt(name: string) {
    return `
<template>
  <div class="page-detail-${kebabCase(name)}">

  </div>
</template>

<script lang="ts" setup>
import dayjs from 'dayjs'

/**
 * 详情组件
 */
defineOptions({ name: '${name}Detail' })

</script>

<style scoped>
.page-detail-${kebabCase(name)} {
  width: 100%;
  height: 100%;
}
</style>
`.trimStart();
}

export function cpFormCt(name: string) {
    return `
<template>
  <div class="page-form-${kebabCase(name)}">

  </div>
</template>

<script lang="ts" setup>
import dayjs from 'dayjs'
import { ref } from 'vue'

/**
 * 表单组件
 */
defineOptions({ name: '${name}Form' })

const formValue = ref<Record<string, any>>({})

const _fMethods = {
  getFormData: () => {
    return JSON.parse(JSON.stringify(formValue.value))
  }
} as const

defineExpose({ ..._fMethods })

</script>

<style scoped>
.page-form-${kebabCase(name)} {
  width: 100%;
  height: 100%;
}
</style>
`.trimStart();
}

export function cpIdxCt(basename: string) {
    return `
<template>
  <div class="page-${kebabCase(basename)}">
    <${basename}Form ref="r${basename}FormRef"/>
  </div>
</template>

<script lang="ts" setup>
import dayjs from 'dayjs'
import { ref, useTemplateRef, onMounted } from 'vue'
import ${basename}Form from './component/${basename}Form.vue'
import ${basename}Detail from './component/${basename}Detail.vue'

/**
 * 列表组件
 */
defineOptions({ name: '${basename}' })
const r${basename}Form = useTemplateRef('r${basename}FormRef')

const submit = async () => {
  const formValue = r${basename}Form.value?.getFormData()
  console.log('formValue: ', formValue)
}

const init = async () => {

}

onMounted(async () => {
  await init()
})
</script>

<style scoped>
.page-${kebabCase(basename)} {
  width: 100%;
  height: 100%;
}
</style>
`.trimStart();
}

export async function createCp(targetPath: vscode.Uri) {
    try {
        // 若已存在则报错，避免无意覆盖
        await vscode.workspace.fs.stat(targetPath);
        throw new Error('目标文件已存在');
    } catch (err: any) {
        if (err?.code === 'FileNotFound' || /ENOENT/i.test(String(err?.message))) {
            const basename = targetPath.path.split('/').pop();
            if (!basename) {
                throw new Error('未获取到文件名');
            }
            const pascalName = pascalCase(basename);
            await vscode.workspace.fs.writeFile(vscode.Uri.joinPath(targetPath, `index.vue`), Buffer.from(cpIdxCt(pascalName), 'utf8'));
            await vscode.workspace.fs.writeFile(vscode.Uri.joinPath(targetPath, `component/${pascalName}Form.vue`), Buffer.from(cpFormCt(pascalName), 'utf8'));
            await vscode.workspace.fs.writeFile(vscode.Uri.joinPath(targetPath, `component/${pascalName}Detail.vue`), Buffer.from(cpDetailCt(pascalName), 'utf8'));
            return;
        }
        throw err;
    }
}
